package com.meatball.authorization.data.entity

import com.meatball.id.base.BaseEntity
import jakarta.persistence.*
import org.hibernate.annotations.Comment
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails

@Entity(name = "USER")
@Comment("用户表")
@Table(
        name = "USER",
        indexes = [
            Index(name = "idex_username", columnList = "username")
        ]
)
data class UserEntity (
    @JvmField
    @Column(name = "username", nullable = false, length = 50, unique = true)
    @Comment("用户名")
    var username: String = "",

    @Column(length = 50)
    @Comment("昵称")
    var nickname: String? = null,

    @Column(length = 50)
    @Comment("真实姓名")
    var realName: String? = null,

    @JvmField
    @Column(name = "password", nullable = false, length = 60)
    @Comment("密码")
    var password: String = "",

    @Comment("头像")
    var avatar: String? = null,

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable
    var roles: Set<RoleEntity> = mutableSetOf()
)  : BaseEntity(), UserDetails {
    /**
     * TODO 获取用户的权限
     * 这里是根据角色枚举的权限来获取的(静态的而非从数据库动态读取)
     *
     * @return 用户权限列表
     */
    override fun getAuthorities(): MutableCollection<out GrantedAuthority> {
        return roles.map { SimpleGrantedAuthority(it.name) }.toMutableSet()
    }

    /**
     * TODO 获取用户密码
     * 主要是用来指定你的password字段
     * @return 用户密码
     */
    override fun getPassword(): String {
        return password
    }

    /**
     * TODO 获取用户账号
     * @return 用户账号
     */
    override fun getUsername(): String {
        return username
    }

    /**
     * TODO 账号是否未过期,下面的这个几个方法都是用来指定账号的状态的,这里全部返回true
     * @return true 未过期
     */
    override fun isAccountNonExpired(): Boolean {
        return true
    }

    /**
     * TODO 账号是否未锁定
     * @return true 未锁定
     */
    override fun isAccountNonLocked(): Boolean {
        return true
    }

    /**
     * TODO 密码是否未过期
     * @return true 未过期
     */
    override fun isCredentialsNonExpired(): Boolean {
        return true
    }

    /**
     * TODO 账号是否激活
     * @return true 已激活
     */
    override fun isEnabled(): Boolean {
        return true
    }
}